package site.yunnong.atvris.service.impl;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import site.yunnong.atvris.common.api.Page;
import site.yunnong.atvris.common.enumeration.MediaTypeEnum;
import site.yunnong.atvris.common.utils.DateUtils;
import site.yunnong.atvris.common.utils.SqlUtils;
import site.yunnong.atvris.dao.domain.UserHistoryView;
import site.yunnong.atvris.dao.domain.UserHistoryViewExample;
import site.yunnong.atvris.dao.domain.Video;
import site.yunnong.atvris.dao.mapper.UserHistoryViewMapper;
import site.yunnong.atvris.service.UserHistoryViewService;
import site.yunnong.atvris.service.UserService;
import site.yunnong.atvris.service.VideoService;
import site.yunnong.atvris.common.dto.HistoryViewParam;
import site.yunnong.atvris.common.dto.HistoryViewQueryParam;
import site.yunnong.atvris.service.helper.OperatorHelper;
import site.yunnong.atvris.service.vo.HistoryViewVO;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户视频历史播放
 *
 * @author zhangjinghao
 * @email jhzhang9102@163.com
 * @date 2021-07-09 23:45:37
 */
@Service
public class UserHistoryViewServiceImpl implements UserHistoryViewService {

    @Autowired
    private UserHistoryViewMapper userHistoryViewMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private VideoService videoService;

    @Override
    public int delete(Long id) {
        return userHistoryViewMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void record(HistoryViewParam param) {
        if (param.getUuid() != null) {
            // 不是匿名的
            UserHistoryViewExample example = new UserHistoryViewExample();
            example.createCriteria().andUuidEqualTo(param.getUuid())
                    .andMediaIdEqualTo(param.getMediaId())
                    .andMediaTypeEqualTo(param.getMediaType());
            List<UserHistoryView> historyViewList = userHistoryViewMapper.selectByExample(example);
            if (CollectionUtils.isEmpty(historyViewList)) {
                // 没有浏览过
                UserHistoryView view = new UserHistoryView();
                BeanUtils.copyProperties(param, view);
                userHistoryViewMapper.insertSelective(view);
            } else {
                // 浏览过，更新浏览记录
                UserHistoryView view = historyViewList.get(0);
                BeanUtils.copyProperties(param, view);
                view.setViewTime(LocalDateTime.now());
                userHistoryViewMapper.updateByPrimaryKey(view);
            }
        }
    }

    @Override
    public int deleteAll() {
        Long uuid = OperatorHelper.getLoginUuid();
        UserHistoryViewExample example = new UserHistoryViewExample();
        example.createCriteria().andUuidEqualTo(uuid);
        return userHistoryViewMapper.deleteByExample(example);
    }

    @Override
    public Page<HistoryViewVO> queryPage(HistoryViewQueryParam param) {
        // uid
        Long uuid = OperatorHelper.getLoginUuid();
        UserHistoryViewExample example = new UserHistoryViewExample();
        example.createCriteria().andUuidEqualTo(uuid);
        // 排序条件
        example.setOrderByClause(SqlUtils.generateOrderByClause("view_time", "desc"));
        com.github.pagehelper.Page<UserHistoryView> historyViewPage = PageHelper.startPage(param.getPageNum(), param.getPageSize())
                .doSelectPage(() -> userHistoryViewMapper.selectByExample(example));
        List<HistoryViewVO> results = Optional.of(historyViewPage.getResult()).orElse(Lists.newArrayList())
                .stream().map(this::buildHistoryViewVO).collect(Collectors.toList());
        return new Page<>(historyViewPage.getPageNum(), historyViewPage.getPageSize(),
                historyViewPage.getTotal(), results);
    }

    private HistoryViewVO buildHistoryViewVO(UserHistoryView userHistoryView) {
        if (MediaTypeEnum.VIDEO.getValue().equals(userHistoryView.getMediaType())) {
            // 查审核通过的视频
            Video video = videoService.queryApprovedVideoByUvid(userHistoryView.getMediaId());
            HistoryViewVO vo = new HistoryViewVO();
            BeanUtils.copyProperties(userHistoryView, vo);
            vo.setUuid(video.getUuid());
            vo.setAvatar(video.getUserAvatar());
            vo.setNickname(video.getUserNickname());
            vo.setUvid(video.getUvid());
            vo.setCover(video.getCover());
            vo.setTitle(video.getTitle());
            vo.setPlayTo(DateUtils.covertSecondToDuration(userHistoryView.getPlayTo() + 1));
            vo.setPid(video.getPid());
            vo.setPartitionName(video.getPartitionName());
            return vo;
        } else {
            // todo 如果支持浏览其他类型媒体，在这里补充
            return null;
        }
    }
}

